import { ref } from 'vue'
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'

interface Tab {
  name: string
  path: string
  isCloseable: boolean
}

export const useTabStore = defineStore('tabs', () => {
  const tabs = ref<Tab[]>([{ name: '首页', path: '/', isCloseable: false }])

  const activeTab = ref('/')

  const router = useRouter()

  function addTab(tab: Tab) {
    if (tabs.value.some((t) => t.path === tab.path)) return
    tabs.value.push(tab)
    activeTab.value = tab.path
  }

  function removeTab(name: string) {
    const index = tabs.value.findIndex((tab) => tab.path === name)
    if (index === -1) return
    tabs.value.splice(index, 1)
    if (activeTab.value === name) {
      activeTab.value = '/'
      router.push('/').then()
    }
  }

  function changeTab(name: string) {
    router.push(name).then()
  }

  function setActiveTab(path: string) {
    activeTab.value = path
  }

  return { tabs, activeTab, addTab, setActiveTab, removeTab, changeTab }
})
